package org.lagou.edu.config;

/**
 * @author shiding
 */
public class HeartBeatMonitor<T> implements Runnable {

    private final T service;
    private final String serviceName;
    private final HeartBeat<T> heartBeat;
    private final long freqMillis;

    public static interface HeartBeat<T> {
        public boolean doHeartBeat(String serviceName, T service);
    }

    private HeartBeatMonitor(String serviceName, T service, HeartBeat<T> heartBeat, long freqMillis) {
        this.serviceName = serviceName;
        this.service = service;
        this.heartBeat = heartBeat;
        this.freqMillis = freqMillis;
    }

    @Override
    public void run() {
        try {
            while (true) {
                Thread.sleep(freqMillis);
                if (!heartBeat.doHeartBeat(serviceName, service)) {
                    break;
                }
            }
        } catch (Exception e) {
        }
    }

    public static <T> void addToKeepAlive(String serviceName, T service, HeartBeat<T> heartBeat, long freqMillis) {
        HeartBeatMonitor<T> monitor = new HeartBeatMonitor<>(serviceName, service, heartBeat, freqMillis);
        Thread monitorThread = new Thread(monitor);
        monitorThread.setDaemon(true);
        monitorThread.start();
    }
}
